package com.xpsoft.oa.service.produce.impl;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.reflect.TypeToken;
import com.xpsoft.core.service.impl.BaseServiceImpl;
import com.xpsoft.core.util.JsonUtil;
import com.xpsoft.oa.dao.produce.MaterialDumpingDao;
import com.xpsoft.oa.dao.produce.MaterialDumpingInfoDao;
import com.xpsoft.oa.model.produce.MaterialDumping;
import com.xpsoft.oa.model.produce.MaterialDumpingInfo;
import com.xpsoft.oa.service.produce.MaterialDumpingService;

public class MaterialDumpingServiceImpl extends BaseServiceImpl<MaterialDumping> implements MaterialDumpingService{
	private MaterialDumpingDao dao;
	@Autowired
	private MaterialDumpingInfoDao materialDumpingInfoDao;
	public MaterialDumpingServiceImpl(MaterialDumpingDao dao) {
		super(dao);
		this.dao=dao;
	}

	@Override
	public void saveMaterialDumping(MaterialDumping materialDumping,
			String dataList) {
		// TODO Auto-generated method stub
		dao.save(materialDumping);
		Boolean isNew = true;//新增标志
		if(materialDumping.getId()!=null){
			isNew = false;
		}
		dao.save(materialDumping);
		if(StringUtils.isNotBlank(dataList)){
			List<MaterialDumpingInfo> materialDumpingInfoList = JsonUtil.fromJsonTypes(dataList,
					new TypeToken<List<MaterialDumpingInfo>>() {
					}.getType());
			if(!isNew){//修改
				List<Long> idList = new ArrayList<Long>();
				for(MaterialDumpingInfo materialDumpingInfo:materialDumpingInfoList){
					if(materialDumpingInfo.getId()!=null){//修改的记录
						idList.add(materialDumpingInfo.getId());
					}
				}
				if(idList.size()>0){//先进行删除
					materialDumpingInfoDao.deleteMaterialDumpingInfos(materialDumping.getId(), idList);
				}
			}
			for(MaterialDumpingInfo materialDumpingInfo:materialDumpingInfoList){
				materialDumpingInfo.setMaterialDumping(materialDumping);
				materialDumpingInfoDao.save(materialDumpingInfo);
			}
		}
	}

}